#include "linux_timer.h"
#include <linux/slab.h>
static void _timer_callback(unsigned long data);
/**
 * @brief Initializes a timer_list structure and set up a timer to call function @callback
 *        after @timeout jiffies.
 * @param callback: The function to be called after timeout.
 * @param data: The parameter to be passed to the callback function.
 * @param timeout: The time after which the callback function will be called.
 * @return A pointer to a newly allocated timer_list structure, or NULL if allocation
 *         failed.
 */
Ltimer* InitTimer(void (*callback)(unsigned long),void* data,uint32_t timeout)
{
    Ltimer* timer =  kmalloc(sizeof(Ltimer),GFP_KERNEL);
        if (!timer) {
        goto fail_init_timer;
    }
    timer->_callback = callback;
    timer->timer = timeout;
    timer->data =(unsigned long) data;
    timer->autoRtimerEn = 1;

    timer->handle.data = (unsigned long)timer;
    timer->handle.function = _timer_callback;
    timer->handle.expires =  jiffies+msecs_to_jiffies(timer->timer);
    printk("start timer = %Xd\n",(unsigned int)timer);
    init_timer(&(timer->handle));
    printk("init timer = %Xd\n",(unsigned int)timer);
    return timer;
fail_init_timer:
    kfree(timer);
    return NULL;
}

int freeTimer(Ltimer *timer)
{
        int flag = 0;
    printk("free timer %xd\n",(unsigned int)timer);

   flag =del_timer(&(timer->handle));//是del_timer的同步版
   printk("del timer %xd flag = %d\n",(unsigned int)timer,flag);
   if(flag) goto faild_del_timer;
    kfree(timer);
    timer = NULL;
    return true;
faild_del_timer:
    return false;
}

void startTimer(Ltimer *timer)
{
    add_timer(&(timer->handle));
}

static void _timer_callback(unsigned long data)
{    
    Ltimer* timer = (Ltimer*)data;
    timer->_callback(timer->data);
    if(timer->autoRtimerEn){
        mod_timer(&(timer->handle),jiffies+msecs_to_jiffies(timer->timer));
    }
}